<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    fullscreen
    v-if="dialogVisible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="dialog-content">
      <el-form :model="form" :rules="rules" label-width="150px" ref="form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装置名称" prop="equipmentName">
              <el-input
                v-model="form.equipmentName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位号" prop="equipmentTag">
              <el-input
                v-model="form.equipmentTag"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采集位号" prop="collectTag">
              <el-input
                v-model="form.collectTag"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="采集位号描述" prop="collectTagDesc">
              <el-input
                type="textarea"
                :rows="4"
                v-model="form.collectTagDesc"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报警分类" prop="alarmClass">
              <el-select
                v-model="form.alarmClass"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="一级" :value="1"></el-option>
                <el-option label="二级" :value="2"></el-option>
                <el-option label="三级" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" class="form-line">
            <el-form-item prop="rangeFilter">
              <template slot="label">
                是否根据量程过滤
                <el-tooltip content="仅保留监测值超出 [量程上下限] 且符合过滤规则（如持续时间、故障等级）的报警信号，屏蔽量程外无效值、瞬时扰动及关联冗余报警，提升报警处理效率" placement="top">
                  <i class="el-icon-question" style="margin-left: 4px; color: #909399; cursor: pointer;"></i>
                </el-tooltip>
              </template>
              <el-radio-group v-model="form.rangeFilter">
                <el-radio :label="1">否</el-radio>
                <el-radio :label="0">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上限" prop="upperLimit">
              <el-input
                type="number"
                v-model="form.upperLimit"
                placeholder="请输入"
                @input="validateLimits"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下限" prop="lowerLimit">
              <el-input
                type="number"
                v-model="form.lowerLimit"
                placeholder="请输入"
                @input="validateLimits"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{
          backgroundColor: '#fafafa',
          fontWeight: 'bold',
          color: '#252525',
        }"
        :row-style="{ height: '50px' }"
        :cell-style="{ padding: '8px 0' }"
        :row-class-name="getRowClassName"
      >
        <el-table-column align="center" type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column align="center" label="报警类型">
          <template slot-scope="scope">
            {{ initName(scope.row.alarmType) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="报警值">
          <template slot-scope="scope">
            <el-input 
              v-model="scope.row.alarmValue" 
              type="number" 
              @input="validateAlarmValue(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="优先级">
          <template slot-scope="scope">
            <el-select 
              v-model="scope.row.alarmLevel" 
              placeholder="请选择"
              @change="clearErrorState(scope.$index)"
            >
              <el-option label="三级" :value="3"></el-option>
              <el-option label="二级" :value="2"></el-option>
              <el-option label="一级" :value="1"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="响应动作" width="400">
          <template slot-scope="scope">
            <el-input v-model="scope.row.alarmProcessMethod" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="响应时间">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.alarmProcessTime"
              placeholder="请选择"
            >
              <el-option label="<5分钟" :value="0"></el-option>
              <el-option label="5-10分钟" :value="1"></el-option>
              <el-option label="10-30分钟" :value="2"></el-option>
              <el-option label="30分钟-1小时" :value="3"></el-option>
              <el-option label="1小时-2小时" :value="4"></el-option>
              <el-option label="2小时以上" :value="5"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="报警原因">
          <template slot-scope="scope">
            <el-input v-model="scope.row.alarmReason" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="报警后果">
          <template slot-scope="scope">
            <el-input v-model="scope.row.alarmConsequence" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  alarmConfigSave,
  alarmConfigUpdate,
} from "@/api/alarmProcess/basicSettings/alarmConfigurationSettings";
export default {
  name: "AlarmConfigurationSettingsDialog",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    editRow: {
      type: Object,
      default: null,
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      tableData: [
        {
          alarmType: 0,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 1,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 2,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 3,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
      ],
      tableErrors: [], // 存储表格行的错误状态
      form: {
        equipmentName: "",
        equipmentTag: "",
        collectTag: null,
        collectTagDesc: "",
        unit: "",
        alarmClass: null,
        rangeFilter: 1,
        upperLimit: null,
        lowerLimit: null,
      },
      rules: {
        equipmentName: [
          { required: true, message: "请输入装置名称", trigger: "blur" },
        ],
        equipmentTag: [
          { required: true, message: "请输入位号", trigger: "blur" },
        ],
        collectTag: [
          { required: true, message: "请输入采集位号", trigger: "blur" },
        ],
        collectTagDesc: [
          { required: true, message: "请输入采集位号描述", trigger: "blur" },
        ],
        unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
        upperLimit: [
          { required: true, message: "请输入上限", trigger: "blur" },
          { validator: this.validateUpperLimit, trigger: "blur" },
        ],
        lowerLimit: [
          { required: true, message: "请输入下限", trigger: "blur" },
          { validator: this.validateLowerLimit, trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    editRow: {
      handler(newVal) {
        this.form = newVal;
        this.tableData = newVal.alarmConfigLevelList;
        this.tableErrors = []; // 重置错误状态
      },
      deep: true,
    },
  },
  methods: {
    // 验证上限
    validateUpperLimit(rule, value, callback) {
      if (value === null || value === undefined || value === "") {
        callback();
        return;
      }
      const upperLimit = parseFloat(value);
      const lowerLimit = parseFloat(this.form.lowerLimit);

      if (!isNaN(lowerLimit) && upperLimit <= lowerLimit) {
        callback(new Error("上限必须大于下限"));
      } else {
        callback();
      }
    },
    // 验证下限
    validateLowerLimit(rule, value, callback) {
      if (value === null || value === undefined || value === "") {
        callback();
        return;
      }
      const lowerLimit = parseFloat(value);
      const upperLimit = parseFloat(this.form.upperLimit);

      if (!isNaN(upperLimit) && lowerLimit >= upperLimit) {
        callback(new Error("下限必须小于上限"));
      } else {
        callback();
      }
    },
    // 实时验证上下限
    validateLimits() {
      this.$nextTick(() => {
        this.$refs.form.validateField("upperLimit");
        this.$refs.form.validateField("lowerLimit");
      });
    },
    // 验证报警值填写时优先级必填
    validateAlarmValue(index) {
      const row = this.tableData[index];
      if (row.alarmValue && row.alarmValue !== '' && row.alarmValue !== null) {
        // 如果报警值已填写，检查优先级是否填写
        if (!row.alarmLevel && row.alarmLevel !== 0) {
          // 设置错误状态
          this.$set(this.tableErrors, index, true);
          this.$message.warning('填写报警值后，优先级为必填项');
        } else {
          // 清除错误状态
          this.$set(this.tableErrors, index, false);
        }
      } else {
        // 清除错误状态
        this.$set(this.tableErrors, index, false);
      }
    },
    // 获取表格行的样式类名
    getRowClassName({ rowIndex }) {
      if (this.tableErrors[rowIndex]) {
        return 'error-row';
      }
      return '';
    },
    // 清除错误状态
    clearErrorState(index) {
      const row = this.tableData[index];
      // 如果报警值已填写且优先级也已填写，清除错误状态
      if (row.alarmValue && row.alarmValue !== '' && row.alarmValue !== null && 
          row.alarmLevel !== null && row.alarmLevel !== undefined) {
        this.$set(this.tableErrors, index, false);
      }
    },
    closeDialog() {
      this.$emit("closeDialog", false);
      this.tableData = [
        {
          alarmType: 0,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 1,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 2,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
        {
          alarmType: 3,
          alarmValue: null,
          alarmLevel: null,
          alarmProcessMethod: null,
          alarmProcessTime: null,
          alarmReason: null,
          alarmConsequence: null,
        },
      ];
      this.tableErrors = []; // 重置错误状态
      this.form = {
        equipmentName: "",
        equipmentTag: "",
        collectTag: null,
        collectTagDesc: "",
        unit: "",
        alarmClass: null,
        rangeFilter: 1,
        upperLimit: null,
        lowerLimit: null,
      };
    },
    initName(val) {
      switch (val) {
        case 0:
          return "高高报";
        case 1:
          return "高报";
        case 2:
          return "低报";
        case 3:
          return "低低报";
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 校验表格数据：如果填写了报警值，优先级必须填写
          let hasInvalidData = false;
          const invalidRows = [];
          
          this.tableData.forEach((row, index) => {
            if (row.alarmValue && row.alarmValue !== '' && row.alarmValue !== null) {
              if (!row.alarmLevel && row.alarmLevel !== 0) {
                hasInvalidData = true;
                invalidRows.push(index + 1);
                // 设置错误状态
                this.$set(this.tableErrors, index, true);
              } else {
                // 清除错误状态
                this.$set(this.tableErrors, index, false);
              }
            } else {
              // 清除错误状态
              this.$set(this.tableErrors, index, false);
            }
          });

          if (hasInvalidData) {
            this.$message.error(`第${invalidRows.join('、')}行：填写报警值后，优先级为必填项`);
            return;
          }

          if (this.title === "编辑") {
            this.form.alarmConfigLevelList = this.tableData;
            alarmConfigUpdate(this.form)
              .then(({ data: res }) => {
                if (res.code === 200) {
                  this.$message.success("编辑成功");
                  this.closeDialog();
                }
              })
              .catch(() => {
                this.$message.error("编辑失败");
              });
          } else {
            this.form.alarmConfigLevelList = this.tableData;
            alarmConfigSave(this.form)
              .then(({ data: res }) => {
                if (res.code === 200) {
                  this.$message.success("添加成功");
                  this.closeDialog();
                }
              })
              .catch(() => {
                this.$message.error("添加失败");
              });
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
// 错误行样式
::v-deep .el-table .error-row {
  background-color: #fef0f0 !important;
  border-color: #f56c6c !important;
}

::v-deep .el-table .error-row:hover > td {
  background-color: #fef0f0 !important;
}

// 错误行中的输入框样式
::v-deep .el-table .error-row .el-input__inner {
  border-color: #f56c6c !important;
}

::v-deep .el-table .error-row .el-select .el-input__inner {
  border-color: #f56c6c !important;
}
</style>
